<template>
  <div class="login-container">
    <div class="login-box">
      <div class="login-header">
        <h2>欢迎登录</h2>
        <p>ZOMIOT 物联网平台</p>
      </div>
      
      <a-form
        :model="formState"
        :rules="rules"
        ref="formRef"
        @finish="handleLogin"
        class="login-form"
      >
        <a-form-item name="username" has-feedback>
          <a-input
            v-model:value="formState.username"
            size="large"
            placeholder="请输入用户名"
          >
            <template #prefix>
              <UserOutlined style="color: rgba(0, 0, 0, 0.25)" />
            </template>
          </a-input>
        </a-form-item>

        <a-form-item name="password" has-feedback>
          <a-input-password
            v-model:value="formState.password"
            size="large"
            placeholder="请输入密码"
          >
            <template #prefix>
              <LockOutlined style="color: rgba(0, 0, 0, 0.25)" />
            </template>
          </a-input-password>
        </a-form-item>

        <a-form-item>
          <a-checkbox v-model:checked="formState.remember">记住我</a-checkbox>
          <a class="login-form-forgot" href="">忘记密码？</a>
        </a-form-item>

        <a-form-item>
          <a-button
            type="primary"
            html-type="submit"
            size="large"
            :loading="loading"
            block
          >
            登录
          </a-button>
        </a-form-item>

        <div class="login-footer">
          还没有账号？<a @click="goToRegister">立即注册</a>
        </div>
      </a-form>
    </div>
  </div>
</template>

<script setup>
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import { UserOutlined, LockOutlined } from '@ant-design/icons-vue'
import { loginApi } from '../api/auth.js'

const router = useRouter()
const formRef = ref()
const loading = ref(false)

// 表单数据
const formState = reactive({
  username: '',
  password: '',
  remember: false
})

// 表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度为3-20个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度为6-20个字符', trigger: 'blur' }
  ]
}

// 处理登录
const handleLogin = async () => {
  try {
    loading.value = true
    
    const response = await loginApi({
      username: formState.username,
      password: formState.password
    })
    
    // 根据实际后端返回的数据结构调整
    if (response.data.code === 200 || response.status === 200) {
      message.success('登录成功！')
      

      
      const token = response.data.token || response.data.data?.token
      const displayName = response.data.displayName || response.data.data?.displayName 
      
  
      // 如果记住我，保存用户信息到 localStorage
      if (formState.remember) {
        localStorage.setItem('username', formState.username)
        localStorage.setItem('displayName', displayName)
        localStorage.setItem('token', token)
      } else {
        // 保存到 sessionStorage
        sessionStorage.setItem('username', formState.username)
        sessionStorage.setItem('displayName', displayName)
        sessionStorage.setItem('token', token)
      }
      
      // 触发自定义事件，通知App组件更新登录状态
      window.dispatchEvent(new Event('userLogin'))
      
      // 跳转到首页
      router.push('/home')
    } else {
      message.error(response.data.message || '登录失败，请检查用户名或密码')
    }
  } catch (error) {
    console.error('登录失败:', error)
    message.error(error.response?.data?.message || '登录失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 跳转到注册页面
const goToRegister = () => {
  router.push('/register')
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

.login-box {
  width: 100%;
  max-width: 400px;
  background: white;
  border-radius: 12px;
  padding: 40px;
  box-shadow: 0 10px 40px rgba(0, 0, 0, 0.1);
}

.login-header {
  text-align: center;
  margin-bottom: 40px;
}

.login-header h2 {
  font-size: 28px;
  font-weight: 600;
  color: #333;
  margin-bottom: 8px;
}

.login-header p {
  font-size: 14px;
  color: #999;
  margin: 0;
}

.login-form {
  margin-top: 20px;
}

.login-form-forgot {
  float: right;
  color: #667eea;
}

.login-form-forgot:hover {
  color: #764ba2;
}

.login-footer {
  text-align: center;
  margin-top: 16px;
  color: #666;
}

.login-footer a {
  color: #667eea;
  font-weight: 500;
}

.login-footer a:hover {
  color: #764ba2;
}

:deep(.ant-input-affix-wrapper) {
  padding: 8px 11px;
}

:deep(.ant-btn-primary) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  height: 44px;
  font-size: 16px;
  font-weight: 500;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}

:deep(.ant-btn-primary):hover {
  background: linear-gradient(135deg, #764ba2 0%, #667eea 100%);
  box-shadow: 0 6px 16px rgba(102, 126, 234, 0.5);
}
</style>

